import { Button, Card, Col, message, Row, Tag, List, Typography, Modal, Select } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer, FooterToolbar, GridContent } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { queryRule, removeRule, getVMAlarmInfos, updateThreshold, syncVMIds } from './service';
import DetailChart from './components/DetailChart';
import UpdateForm from './components/UpdateForm';
import './server.less';

/**
 *  删除节点
 * @param selectedRows
 */

const handleRemove = async (selectedRows) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    await removeRule({
      idList: selectedRows.map((row) => row.id),
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList = () => {
  const ListItem = List.Item;
  const { Option } = Select;
  const actionRef = useRef();
  const [selectedRowsState, setSelectedRows] = useState([]);
  const [clickRowsValue, setClickRows] = useState({});
  const [detailModalVisible, handleDetailModalVisible] = useState(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState(false);
  const [reqTimeBarData] = useState([]);
  const [stepFormValues, setStepFormValues] = useState({});
  const [value, setValue] = useState({});
  const [alarmValue, setAlarmValue] = useState({});
  const [timeLine, setTimeLine] = useState([]);
  const [timer, setTimer] = useState(null);

  function queryVMInfos(params) {
    getVMAlarmInfos(params).then((res) => {
      if (res.status === 200) {
        getAlarmBarData(res.data.cpuAlarmList, res.data.memoryAlarmList, res.data.netAlarmList);
        handleDetailModalVisible(true);
      }
    });
  }

  function handleVMIDSysnc() {
    message.loading('正在同步');
    syncVMIds().then((res) => {
      if (res.status === 200) {
        message.success(res.message);
        if (actionRef.current) {
          actionRef.current.reload();
        }
      } else {
        message.error(res.message);
        if (actionRef.current) {
          actionRef.current.reload();
        }
      }
    });
  }

  function handleDetailModal(record) {
    message.loading('正在查询');
    const params = {
      id: record.id,
    };
    queryVMInfos(params);
    if (timer == null) {
      const dingShi = setInterval(() => {
        queryVMInfos(params);
      }, 30 * 1000);
      setTimer(dingShi);
    }
  }

  /**
   *  更新或新增接口
   * @param selectedRows
   */

  const handleUpdate = async (row) => {
    message.loading('正在操作', 0);
    await updateThreshold(row)
      .then((res) => {
        if (res.status === 200) {
          message.destroy();
          message.success('操作成功');
          handleUpdateModalVisible(false);
          setStepFormValues({});
          if (actionRef.current) {
            actionRef.current.reload();
          }
          return;
        }
        message.destroy();
        message.error(res.message);
      })
      .catch(() => {
        message.destroy();
        message.error('操作失败，请检查参数再重试');
      });
  };

  function getAlarmBarData(cpuAlarmList, memoryAlarmList, netAlarmList) {
    const typeValue = {};
    const typeAlarmValue = {};
    const cpuData = [];
    const cpuAlarm = [];
    const memoryData = [];
    const memoryAlarm = [];
    const netData = [];
    const netAlarm = [];

    // eslint-disable-next-line array-callback-return
    cpuAlarmList.map((item) => {
      const cpuDataItem = {};
      const cpuAlarmItem = {};
      cpuDataItem.name = item.datecreated;
      cpuDataItem.value = [item.datecreated, item.cpuvalue];
      cpuAlarmItem.name = item.datecreated;
      cpuAlarmItem.value = [item.datecreated, item.cputhreshold];

      cpuData.push(cpuDataItem);
      cpuAlarm.push(cpuAlarmItem);
    });

    // eslint-disable-next-line array-callback-return
    memoryAlarmList.map((item) => {
      const memoryDataItem = {};
      const memoryAlarmItem = {};
      memoryDataItem.name = item.datecreated;
      memoryDataItem.value = [item.datecreated, item.memoryvalue];
      memoryAlarmItem.name = item.datecreated;
      memoryAlarmItem.value = [item.datecreated, item.memorythreshold];

      memoryData.push(memoryDataItem);
      memoryAlarm.push(memoryAlarmItem);
    });

    // eslint-disable-next-line array-callback-return
    netAlarmList.map((item) => {
      const netDataItem = {};
      const netAlarmItem = {};
      netDataItem.name = item.datecreated;
      netDataItem.value = [item.datecreated, item.netvalue];
      netAlarmItem.name = item.datecreated;
      netAlarmItem.value = [item.datecreated, item.netthreshold];

      netData.push(netDataItem);
      netAlarm.push(netAlarmItem);
    });

    const now = new Date();
    const begin = `${now.getFullYear()}-${now.getMonth()}${1}-${now.getDate()} 00:00:00`;
    const end = `${now.getFullYear()}-${now.getMonth()}${1}-${now.getDate()} 24:00:00`;
    const timeLines = [
      { name: begin, value: [begin, 0] },
      { name: end, value: [end, 0] },
    ];

    typeValue.cpuData = cpuData; // cpu当前值
    typeAlarmValue.cpuAlarm = cpuAlarm; // cpu告警阀值
    typeValue.memoryData = memoryData; // 内存当前值
    typeAlarmValue.memoryAlarm = memoryAlarm; // 内存告警阀值
    typeValue.netData = netData; // 网络当前值
    typeAlarmValue.netAlarm = netAlarm; // 网络告警阀值

    setValue(typeValue); // 当前值
    setAlarmValue(typeAlarmValue); // 告警阀值
    setTimeLine(timeLines); // 时间轴
  }

  const columns = [
    {
      title: '资产ID',
      dataIndex: 'id',
      key: 'id',
      sorter: true,
      ellipsis: true,
      width: '10%',
    },
    {
      title: 'HOST名称',
      key: 'hostname',
      dataIndex: 'hostname',
      ellipsis: true,
      width: '15%',
    },
    {
      title: '内网IP',
      key: 'ip',
      dataIndex: 'ip',
      width: '10%',
    },
    {
      title: 'cpu告警阀值',
      key: 'cputhreshold',
      dataIndex: 'cputhreshold',
      width: '10%',
      hideInTable: true,
      search: false,
    },
    {
      title: '内存告警阀值',
      key: 'memorythreshold',
      dataIndex: 'memorythreshold',
      width: '10%',
      hideInTable: true,
      search: false,
    },
    {
      title: '网络告警阀值',
      key: 'netthreshold',
      dataIndex: 'netthreshold',
      width: '10%',
      hideInTable: true,
      search: false,
    },
    /* {
      title: '磁盘告警阀值',
      key: 'diskthreshold',
      dataIndex: 'diskthreshold',
      width: 120,
      hideInTable: true,
      search: false,
    }, */
    {
      title: '硬件配置',
      key: 'hardwareinfo',
      dataIndex: 'hardwareinfo',
      ellipsis: true,
      width: '15%',
      render: (text, record) => {
        return (
          <Tag color="blue" key={record.hardwareinfo}>
            {text}
          </Tag>
        );
      },
    },
    {
      title: '操作系统',
      key: 'os',
      dataIndex: 'os',
      width: '10%',
      render: (text, record) => {
        return (
          <Tag color="orange" key={record.os}>
            {`${text} ${record.osversion}`}
          </Tag>
        );
      },
    },
    {
      title: '区域',
      key: 'area',
      dataIndex: 'area',
      ellipsis: true,
      width: '15%',
    },
    {
      title: '是否在线',
      key: 'isactive',
      dataIndex: 'isactive',
      width: '8%',
      renderFormItem: () => {
        return (
          <Select
            key="onlineSelect"
            showSearch
            placeholder="请选择在线状态"
            filterOption={false}
            defaultValue=""
          >
            <>
              <Option key="3" value="">
                全部
              </Option>
              <Option key="1" value="true">
                在线
              </Option>
              <Option key="2" value="false">
                掉线
              </Option>
            </>
          </Select>
        );
      },
      render: (text, record) => {
        const color = record.isactive === 'true' ? 'green' : 'red';
        return (
          <Tag color={color} key={record.isactive}>
            {text === 'true' ? '在线' : '掉线'}
          </Tag>
        );
      },
    },
    {
      title: '操作',
      key: 'option',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => {
        let colorVal = '#808A87';
        let disabledVal = true;
        if (record.area.substring(0, 4) === '电信机房') {
          colorVal = '#009688';
          disabledVal = false;
        }
        return (
          <>
            <Button
              type="primary"
              size="small"
              onClick={() => {
                setStepFormValues(record);
                handleDetailModal(record);
              }}
              style={{ background: colorVal, borderColor: colorVal }}
              disabled={disabledVal}
            >
              查看
            </Button>
            &nbsp;
            <Button
              type="primary"
              size="small"
              onClick={() => {
                handleUpdateModalVisible(true);
                setStepFormValues(record);
              }}
              style={{ background: colorVal, borderColor: colorVal }}
              disabled={disabledVal}
            >
              阀值
            </Button>
          </>
        );
      },
    },
  ];

  return (
    <PageContainer>
      <GridContent>
        <Row gutter={24}>
          <Col lg={17} md={24}>
            <ProTable
              headerTitle="查询表格"
              actionRef={actionRef}
              rowKey="key"
              request={(params, sorter, filter) =>
                queryRule({
                  ...params,
                  sorter,
                  filter,
                  areaType:
                    window.location.href.indexOf('?area=') > -1
                      ? window.location.href.split('?area=')[1]
                      : '',
                })
              }
              columns={columns}
              rowSelection={{
                onChange: (_, selectedRows) => setSelectedRows(selectedRows),
              }}
              toolBarRender={() => [
                <Button type="primary" onClick={() => handleVMIDSysnc()}>
                  服务器同步
                </Button>,
              ]}
              onRow={(record) => {
                return {
                  onClick: () => {
                    setClickRows(record);
                  },
                };
              }}
            />
            {selectedRowsState?.length > 0 && (
              <FooterToolbar
                extra={
                  <div>
                    已选择{' '}
                    <a
                      style={{
                        fontWeight: 600,
                      }}
                    >
                      {selectedRowsState.length}
                    </a>{' '}
                    项
                  </div>
                }
              >
                <Button
                  type="primary"
                  danger
                  onClick={async () => {
                    await handleRemove(selectedRowsState);
                    setSelectedRows([]);
                    actionRef.current?.reloadAndRest();
                  }}
                >
                  批量删除
                </Button>
              </FooterToolbar>
            )}
          </Col>
          <Col lg={7} md={24}>
            <Card
              title="服务器配置详情"
              headStyle={{ textAlign: 'center', fontWeight: 'bold', borderBottomColor: '#e0dddd' }}
              style={{ backgroundColor: '#e6f7ffe3' }}
            >
              <List itemLayout="horizontal" size="large">
                <ListItem>
                  <Typography.Text>资产ID：</Typography.Text> <span>{clickRowsValue.id}</span>
                </ListItem>
                <ListItem>
                  <Typography.Text>VMID：</Typography.Text> <span>{clickRowsValue.vMId}</span>
                </ListItem>
                <ListItem>
                  <Typography.Text>资产标签：</Typography.Text> <span>{clickRowsValue.labels}</span>
                </ListItem>
                <ListItem>
                  <Typography.Text>SN序号：</Typography.Text> <span>{clickRowsValue.sn}</span>
                </ListItem>
                <ListItem>
                  <Typography.Text>HOST名称：</Typography.Text>{' '}
                  <span>{clickRowsValue.hostname}</span>
                </ListItem>
                <ListItem>
                  <Typography.Text>公网IP：</Typography.Text> <span>{clickRowsValue.publicip}</span>
                </ListItem>
                <ListItem>
                  <Typography.Text>内网IP：</Typography.Text> <span>{clickRowsValue.ip}</span>
                </ListItem>
                <ListItem>
                  <Typography.Text>硬件配置：</Typography.Text>{' '}
                  <span>{clickRowsValue.hardwareinfo}</span>
                </ListItem>
                <ListItem>
                  <Typography.Text>机器型号：</Typography.Text> <span>{clickRowsValue.model}</span>
                </ListItem>
                <ListItem>
                  <Typography.Text>系统名称：</Typography.Text> <span>{clickRowsValue.os}</span>
                </ListItem>
                <ListItem>
                  <Typography.Text>系统架构：</Typography.Text> <span>{clickRowsValue.osarch}</span>
                </ListItem>
                <ListItem>
                  <Typography.Text>系统版本：</Typography.Text>{' '}
                  <span>{clickRowsValue.osversion}</span>
                </ListItem>
                <ListItem>
                  <Typography.Text>系统类型：</Typography.Text>{' '}
                  <span>{clickRowsValue.platform}</span>
                </ListItem>
                <ListItem>
                  <Typography.Text>制造商：</Typography.Text> <span>{clickRowsValue.area}</span>
                </ListItem>
                <ListItem>
                  <Typography.Text>创建时间：</Typography.Text>{' '}
                  <span>{clickRowsValue.datecreated}</span>
                </ListItem>
              </List>
            </Card>
          </Col>
        </Row>
      </GridContent>

      {detailModalVisible ? (
        <Modal
          className={'serverSty'}
          width={1300}
          height={800}
          destroyOnClose
          confirmLoading={false}
          onCancel={() => {
            handleDetailModalVisible(false);
            if (timer !== null) {
              clearInterval(timer);
              setTimer(null);
            }
          }}
          cancelText="关闭"
          footer={[]}
          title={
            <div
              style={{
                width: '100%',
              }}
            >
              服务器监控报表
            </div>
          }
          visible={detailModalVisible}
        >
          <DetailChart
            reqTimeBarData={reqTimeBarData}
            value={value}
            alarmValue={alarmValue}
            timeLine={timeLine}
          />
        </Modal>
      ) : null}

      {updateModalVisible ? (
        <UpdateForm
          key="updateModal"
          onSubmit={async (values) => {
            await handleUpdate(values);
          }}
          onCancel={() => {
            handleUpdateModalVisible(false);
            setStepFormValues({});
          }}
          updateModalVisible={updateModalVisible}
          values={stepFormValues}
        />
      ) : null}
    </PageContainer>
  );
};

export default TableList;
